<?php
namespace app\seller\controller;
use think\Controller;
use think\facade\Request;
use think\captcha\Captcha;
class Login extends Controller{
    protected $sys;
    public function initialize(){
        if (session('seller.id')) {
            $this->redirect('index/index');
        }
        $this->sys = cache('System');
        $this->assign('sys',$this->sys);
    }
    public function index(){
        if(request()->isPost()) {
            $table = db('shop');  
            $request = Request::instance();  
            $username = input('username');
            $password = input('password');
            if($this->sys['code']=='open'){
                $code = input('vercode');
                if(!$this->check($code)) return array('code' => 0, 'msg' => '验证码错误');
            }
            if(!$username || !$password) return array('code'=>0,'msg'=>'请填写账号或密码');
            $user = $table->where("mobile","=",$username)->find();
            if(!$user){
                return array('code'=>0,'msg'=>'账号不存在!');
            }elseif(md5($password) != $user['password']){ 
                return array('code'=>0,'msg'=>'密码错误!');
            }elseif($user['open'] == 0){
                return array('code'=>0,'msg'=>'账号异常已被锁定！！！');
            }else{ 
                $sessionUser = $table->where("id",'=',$user['id'])->find();
                if($sessionUser){
                    session('seller',$sessionUser);
                    return array('code'=>1,'msg'=>'登录成功','url' => url('index/index'));
                }else{
                    return array('code'=>-1,'msg'=>'登录失败');
                } 
            }
        }else{
            $this->assign('title','商家登录');
            return $this->fetch();
        }
    }  
    // 图形验证码
    public function verify(){
        $config =    [
            // 验证码字体大小
            'fontSize'    =>    25,
            // 验证码位数
            'length'      =>    4,
            // 关闭验证码杂点
            'useNoise'    =>    false,
            'bg'          =>    [255,255,255],
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }
    // 检测验证码
    public function check($code){
        return captcha_check($code);
    }
}